package com.cefa.edu.common;

import com.alibaba.fastjson.JSON;
import com.cefa.edu.common.result.FailureResult;
import com.cefa.edu.common.result.ReturnMessage;
import com.cefa.edu.util.SignUtil;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Created by qimwang on 8/1/17.
 */
@Configuration
public class SignVerifyInterceptor implements HandlerInterceptor {

    @Value("${application.sign}")
    String sign;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object var3) throws Exception {
        Map<String, String[]> params = request.getParameterMap();
        List<String> keyList = Lists.newArrayList(params.keySet());
        Collections.sort(keyList);
        keyList.remove("sign");
        StringBuilder sb = new StringBuilder();
        for(String paramKey : keyList){
            String paramValue = request.getParameter(paramKey);
           // if(StringUtils.isNotEmpty(paramValue)) {
                sb.append(paramKey);
                sb.append('=');
                sb.append(paramValue);
                sb.append('&');
           // }
        }

        sb.deleteCharAt(sb.length() - 1);
        String encryptedStr = SignUtil.build(SignUtil.SignMethod.MD5).sign(sb.toString(), sign);
        System.out.println(encryptedStr);
        System.out.println("interceptor");
        if (encryptedStr == null) {
            return false;
        }
        boolean verify = encryptedStr.equalsIgnoreCase(request.getParameter("sign"));
        if (!verify) {
            String jsonContent = JSON.toJSONString(new FailureResult(new ReturnMessage("400", "签名失败")));
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.setHeader("Access-Control-Allow-Origin","*");
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().append(jsonContent);
            response.getWriter().flush();
        }
        return verify;
    }

    public void postHandle(HttpServletRequest var1, HttpServletResponse var2, Object var3, ModelAndView var4) throws Exception {

    }

    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object var3, Exception var4) throws Exception {

    }

}
